<template>
  <div style="width: 300px">
    <div class="toRegister">
      <h2>Sign in to</h2>
      <h2>Open the word</h2>
    </div>
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      :rules="rules"
      size="large"
      status-icon
    >
      <el-form-item prop="username">
        <el-input
          v-model="ruleForm.username"
          placeholder="请输入用户名"
          style="width: 100%"
        />
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          v-model="ruleForm.password"
          type="password"
          placeholder="请输入密码"
          style="width: 100%"
        />
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          v-model="ruleForm.passwordAgin"
          type="password"
          placeholder="请输入密码"
          style="width: 100%"
        />
      </el-form-item>
      <!-- <el-form-item prop="verifyCode">
              <div style="display:flex;justify-content:space-between;width: 100%;">
                <el-input v-model="ruleForm.verifyCode"  placeholder="验证码" style="flex: 1;margin-right: 10px;"/>
                <img :src="codeImg" alt="" style="width:120px">
              </div>
          </el-form-item> -->
      <el-form-item>
        <el-button
          @click="showRegist"
          size="large"
          color="#4460ED"
          style="width: 100%; box-shadow: 0px 5px 10px 0 #8c9eeb"
          >去登录</el-button
        >
      </el-form-item>
      <el-form-item>
        <el-button
          @click="toRegist(ruleFormRef)"
          :loading="loading"
          size="large"
          color="#FC313A"
          style="width: 100%; box-shadow: 0px 5px 10px 0 #fea4a8"
          class="register"
          >点击注册</el-button
        >
      </el-form-item>
      <el-form-item>
        <el-divider>
          <span style="color: gray">or continue width</span>
        </el-divider>
      </el-form-item>
      <el-form-item>
        <div class="other">
          <div class="iconfont icon-google"></div>
          <div class="iconfont icon-twitter-fill"></div>
          <div class="iconfont icon-weixin"></div>
        </div>
      </el-form-item>
      <!-- box-shadow:-10px 0px 10px red,   /*左边阴影*/
          0px -10px 10px #000,  /*上边阴影*/
          10px 0px 10px green,  /*右边阴影*/
          0px 10px 10px blue;" -->
    </el-form>
  </div>
</template>

<script lang="ts" setup>
import { ElNotification } from "element-plus";
import { regist } from "@/api/login/login";
import type { FormInstance } from "element-plus";
// import { getCaptcha } from '@/api/login/login';
import router from "@/router";
import {
  toRefs,
  toRef,
  reactive,
  ref,
  onMounted,
  getCurrentInstance,
  watch,
  computed,
  customRef,
  defineEmits,
} from "vue";

import useStore from "@/store";

import { useRoute } from "vue-router";
const route = useRoute();
const { user } = useStore();

/**
 * 切换登陆注册窗口
 */
const emits = defineEmits(["changeType"]);
const showRegist = () => {
  console.log(555);

  emits("changeType");
};

const state = reactive({
  redirect: "",
  otherQuery: {},
  ruleForm: {
    username: "",
    password: "",
    passwordAgin: "",
    // grant_type:'captcha',
    // verifyCodeKey:'',
    // verifyCode:'',
  },
  rules: {
    username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
    password: [{ required: true, validator: validatePassword }],
    passwordAgin: [{ required: true, validator: validatePassword }],
  },
  codeImg: "",
  loading: false,
});

watch(
  route,
  (newval, oldval) => {
    const query = route.query;
    if (query) {
      state.redirect = query.redirect as string;
      state.otherQuery = getOtherQuery(query);
    }
  },
  {
    immediate: true,
  }
);

function getOtherQuery(val: any) {
  return Object.keys(val).reduce((a: any, b: any) => {
    if (b != "redirect") {
      a[b] = val[b];
    }
    return a;
  }, {});
}

const { ruleForm, rules, loading, codeImg } = toRefs(state);

function validatePassword(rule: any, value: String, callBack: Function) {
  if (value.length <= 4) {
    callBack(new Error("密码长度不得少于4位"));
  } else {
    callBack();
  }
}

// const pageInstance = getCurrentInstance();
// const loginForm = pageInstance.refs.loginFormRef
/**
 * 注册
 */
const ruleFormRef = ref<FormInstance>(); //表单组件
const toRegist = (el: FormInstance | undefined) => {
  if (el) {
    el.validate((valid: boolean) => {
      if (valid) {
        loading.value = true;
        regist({
          username: ruleForm.value.username,
          password: ruleForm.value.password,
        }).then((res: any) => {
          loading.value = false;
          if (res.data.code == 200) {
            el.resetFields();
            ElNotification({
              title: res.data.msg,
              message: "已成功注册",
              duration: 2000,
              type: "success",
            });
            emits("changeType");
          }
        });
      }
    });
  } else {
    alert("DOM获取失败");
  }
};

/**
 * 获取验证码
 */
//  function getCaptchaImg(){
//     getCaptcha().then((res:any)=>{
//         ruleForm.value.verifyCodeKey=res.data.data.verifyCodeKey
//         codeImg.value = res.data.data.verifyCodeImg
//     })
//  }
//  getCaptchaImg()

// 计算属性学习
// state.ruleForm.username = computed({
//   get(){
//     return value
//   },
//   set(value:String){
//     console.log(44);
//     return value

//   }
// })
// state.ruleForm.username = computed(()=>{
//   return 777
// })

// 监听学习
// 情况1
// watch(state,(newval,oldval)=>{
//   console.log('sss');
// },{immediate:true,deep:true})
// watch([a,b],(newval,oldval)=>{
// newval也会是数组
//   console.log('sss');
// },{immediate:true})
// 监测ref对象也需要带value
// 如果是监视一个对象则不会检测到老数据

// 监测reactive某一个属性需要携程函数返回的格式，并且oldvalue好用
// watch(()=>ruleForm.username,(newval,oldval)=>{
//   console.log('sss');
// },{immediate:true，deep:true})  监测具体属性为对象的时候deep属性有用

// watchEffect 监测所有数据
// watchEffect(() => {
//   console.log("立即执行");
// 用谁监测谁
// });

// 生命周期
// onMounted(()=>{

// })
// 组件传值
// let emigFun = defineEmits(["handLer"])//自定义事件

// const props = defineProps({
//   msg: String,
//   DateList: Array,
// }); //接收参数

// toRef 变成一个ref对象
// const username = toRef(ruleForm,'username')
// toRefs//批量转化
// const a = toRefs(ruleForm)

// 响应式数据转原始数据 toRow,只能处理reactive处理的响应式数据
// const a = toRow(person)

// 自定义ref   customRef
// const myRef = (value:any) => {
//   return customRef((track,trigger)=>{
//     return {
//       get:()=>{
//         track()//通知监测
//         return value
//       },
//       set:(newValue)=>{
//         console.log("所需要的操作");
//         value = newValue
//       }
//     }
//   })
// }
// 所需要的数据
// const a = myRef("66")

// provide('name', 'value');//传递数据，（自定义名字，传递的值）
//  const a =  inject('name') //子组件获取值

// 新增组件teleport 传送
// <teleport to="html">
//     //里面鞋内融即可
// </teleport>

// Vue.protoType=====app.config.globalProperties
</script>

<style lang="scss" scoped>
.el-input {
  display: inline-block;
  height: 36px;
  width: 85%;
  :deep(.el-input__wrapper) {
    box-shadow: none;
    background: #f1f5fd;
    display: flex;
  }
  :deep(.el-input__wrapper:hover) {
    box-shadow: none;
  }
}
.el-form-item--large :deep(.el-form-item__error) {
  padding-top: 6px;
}
.other {
  display: flex;
  width: 100%;
  justify-content: space-around;
  > div {
    width: 50px;
    height: 50px;
    line-height: 50px;
    text-align: center;
    font-size: 30px;
    border-radius: 8px;
    box-shadow: 0px 10px 10px #e3e3e3;
    transition: all 0.5s;
  }
  > div:hover {
    background: gray;
    color: white;
  }
}
@media screen and (max-width: 800px) {
  .register {
    display: block;
  }
  .toRegister {
    display: block;
  }
}
@media screen and (min-width: 800px) {
  /* .register{
  display: none;
} */
  .toRegister {
    display: none;
  }
}
.toRegister {
  font-size: 20px;
  color: black;
  margin-bottom: 20px;
}
</style>
